package com.keyinong.caizhengting.adapter;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.keyinong.caizhengting.R;
import com.keyinong.caizhengting.tools.HttpTools;
import com.keyinong.caizhengting.tools.ImageUtils;
import com.keyinong.caizhengting.tools.NetWorkUtil;
import com.keyinong.caizhengting.activity.FanqiedingcanActivity;
import com.keyinong.caizhengting.activity.GoodsTwoSortActivity;
import com.keyinong.caizhengting.entity.ShangpinEntity;
import com.loopj.android.http.JsonHttpResponseHandler;

import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

/**
 * @author：郑谦
 * @时间：2016-12-19 下午3:00:44
 * @类名：SearchAdapter.java
 * @功能: 搜索适配器
 */
public class SearchAdapter extends BaseAdapter {
    Context context;
    ArrayList<ShangpinEntity> shangpinList;
    //	ArrayList<ShangpinEntity> shangpinList;
    HttpTools httpTools = null;

    public SearchAdapter(Context context, ArrayList<ShangpinEntity> shangpinList) {
        super();
        this.context = context;
        this.shangpinList = shangpinList;
    }

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return shangpinList.size();
    }

    @Override
    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return shangpinList.get(position);
    }

    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override
    public View getView(final int position, View view, ViewGroup parent) {
        final ViewHandle handle;
        if (view == null) {
            handle = new ViewHandle();
            view = LayoutInflater.from(context).inflate(R.layout.item_dinner, null);
            handle.iv_shangpin = (ImageView) view.findViewById(R.id.imageView1);
            handle.tv_shangpinming = (TextView) view.findViewById(R.id.tv_shangpinming5);
            //			handle.tv_content=(TextView)view.findViewById(R.id.tv_content);
            handle.tv_price = (TextView) view.findViewById(R.id.tv_price5);
            handle.ib_add = (ImageButton) view.findViewById(R.id.ib_add5);
            handle.ib_less = (ImageButton) view.findViewById(R.id.ib_less5);
            handle.et_amout = (EditText) view.findViewById(R.id.et_amount5);
            handle.tv_xiangliang = (TextView) view.findViewById(R.id.tv_xiaoliang);
            handle.tv_xiangou = (TextView) view.findViewById(R.id.tv_xiangou);
            //			if (!shangpinList.get(position).getArraylength().equals("0")) {
            //				handle.tv_guige.setVisibility(View.VISIBLE);
            //				handle.et_amout.setVisibility(View.GONE);
            //				handle.ib_add.setVisibility(View.GONE);
            //				handle.ib_less.setVisibility(View.GONE);
            //
            //			}else if(shangpinList.get(position).getArraylength().equals("0")){
            //				handle.tv_guige.setVisibility(View.GONE);
            //				handle.et_amout.setVisibility(View.VISIBLE);
            //				handle.ib_add.setVisibility(View.VISIBLE);
            //				handle.ib_less.setVisibility(View.VISIBLE);
            //			}
            view.setTag(handle);
        } else {
            handle = (ViewHandle) view.getTag();
        }
        if (shangpinList.get(position).getPerlim().equals("0")) {
            handle.tv_xiangou.setVisibility(View.GONE);
            handle.tv_xiangliang.setText("月销量" + shangpinList.get(position).getSellnum() + shangpinList.get(position).getUnit());
        } else {
            handle.tv_xiangou.setVisibility(View.VISIBLE);
            handle.tv_xiangliang.setText("剩余" + shangpinList.get(position).getStock() + ",限购" + shangpinList.get(position).getPerlim());
        }
        handle.tv_shangpinming.setText(shangpinList.get(position).getName());
        //		handle.tv_content.setText(shangpinList.get(position).getContent());
        handle.tv_price.setText(shangpinList.get(position).getPrice());
        handle.et_amout.setText(shangpinList.get(position).getAmount());
        ImageUtils.displayImage(
                context,
                (shangpinList.get(position).getImage() + "?imageView2/1/w/360/h/300").replace("w/60", "w/120"),
                handle.iv_shangpin, R.drawable.wupian1);

        /**加购物车*/
        handle.ib_add.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                //				if (NetWorkUtil.isNetwork(context) == false) {
                //					Toast.makeText(context, "当前网络不可用", 1).show();
                //					return;
                //				}
                //				if ("".equals(handle.et_amout.getText().toString())) {
                //					handle.et_amout.setText(0 + "");
                //				}
                //				int goodsNum = Integer.parseInt(handle.et_amout
                //						.getText().toString());
                //				goodsNum++;
                //				handle.et_amout.setText(goodsNum + "");
                //				addGoods(position, handle.et_amout,handle.tv_xiangliang);
//				int goodsNum = Integer.parseInt(handle.et_amout.getText().toString());
//				goodsNum++;
//				if (goodsNum>=Integer.parseInt(shangpinList.get(position).getPerlim())&& !shangpinList.get(position).getPerlim().equals("0")) {
//					Toast.makeText(context, "每人限购"+shangpinList.get(position).getPerlim()+"份", Toast.LENGTH_SHORT).show();
//					return;
//				}


                int num = Integer.parseInt(shangpinList.get(position).getPerlim()) - Integer.parseInt(shangpinList.get(position).getBuyamount());
                ;
                int goodsNum = Integer.parseInt(handle.et_amout.getText().toString());
                goodsNum++;
                if (goodsNum > num && !shangpinList.get(position).getPerlim().equals("0")) {
                    Toast.makeText(context, "每人限购" + shangpinList.get(position).getPerlim() + "份", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (goodsNum > Integer.parseInt(shangpinList.get(position).getStock())) {
                    Toast.makeText(context, "库存不足,还剩" + shangpinList.get(position).getStock() + "份", Toast.LENGTH_SHORT).show();
                    return;
                }
                handle.et_amout.setText("" + goodsNum);
                addGoods(position, handle.et_amout, goodsNum, handle.tv_xiangliang);
            }
        });
        /**减少购物车*/
        handle.ib_less.setOnClickListener(new OnClickListener() {
            int goodsNum;

            @Override
            public void onClick(View v) {
                //				if ("".equals(handle.et_amout.getText().toString())) {
                //					handle.et_amout.setText(0 + "");
                //					goodsNum = 0;
                //				} else {
                //					goodsNum = Integer.parseInt(handle.et_amout
                //							.getText().toString());
                //				}
                //				if (goodsNum > 0) {
                //					goodsNum--;
                //				}
                //				handle.et_amout.setText(goodsNum + "");
                //				addgoodscat(position, handle.et_amout);
                int goodsNum = Integer.parseInt(handle.et_amout.getText().toString());
                goodsNum--;
                if (goodsNum < 0) {
                    Toast.makeText(context, "数量不能小于0", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (goodsNum == 0) {
                    deletegoods(position, goodsNum);
                    goodsNum = 0;
                    handle.et_amout.setText("0");
                    return;
                }

                handle.et_amout.setText("" + goodsNum);
                lessGoods(position, handle.et_amout, goodsNum, handle.tv_xiangliang);
            }
        });


        return view;
    }

    /**
     * 增加商品
     */
    private void addGoods(final int index, final EditText editText, final int goodsNum, final TextView tv) {
        if (NetWorkUtil.isNetwork(context) == false) {
            Toast.makeText(context, "当前网络不可用", Toast.LENGTH_SHORT).show();
            return;
        }
        if ("".equals(editText.getText().toString())) {
            editText.setText(0 + "");
        }
        SharedPreferences sp = context.getSharedPreferences("spReg",
                Context.MODE_PRIVATE);
        String token = sp.getString("data", "");
        if (httpTools == null) {
            httpTools = new HttpTools(context);
        }
//		int goodsNum = Integer.parseInt(editText.getText().toString());
//		goodsNum++;
////		if (goodsNum>Integer.parseInt(shangpinList.get(index).getPerlim())&& !shangpinList.get(index).getPerlim().equals("0")) {
////			Toast.makeText(context, "每人限购"+shangpinList.get(index).getPerlim()+"份", Toast.LENGTH_SHORT).show();
////			return;
////		}
////		if (goodsNum>Integer.parseInt(shangpinList.get(index).getStock())) {
////			Toast.makeText(context, "库存不足,还剩"+shangpinList.get(index).getStock()+"份", Toast.LENGTH_SHORT).show();
////			return;
////		}
        httpTools.addgoodscat(token, shangpinList.get(index).getId(), goodsNum + "",
                new JsonHttpResponseHandler() {

                    @Override
                    public void onSuccess(int statusCode, Header[] headers,
                                          JSONObject response) {
                        // TODO Auto-generated method stub
                        super.onSuccess(statusCode, headers, response);
                        try {
                            Log.i("zq", response.toString());
                            boolean code = response.getBoolean("code");
                            String msg = response.getString("msg");
                            int goodsNum = Integer.parseInt(editText.getText().toString());
                            if (code == true) {
                                JSONObject data = response.getJSONObject("data");
                                String amount = data.getString("amount");
                                String total = data.getString("total");
//						int goodsNum = Integer.parseInt(editText.getText().toString());
//						goodsNum++;
                                editText.setText(goodsNum + "");
//						int lim = Integer.parseInt(shangpinList.get(index).getPerlim());
//						int stock = Integer.parseInt(shangpinList.get(index).getStock());
                                //						if(goodsNum==stock){
                                //							tv.setVisibility(View.VISIBLE);
                                //							tv.setText("库存不足，仅剩"+shangpinList.get(index).getStock()+"份");
                                //							goodsNum=stock;
                                //							editText.setText(goodsNum);
                                //						}
                                //							else {
                                //							tv.setVisibility(View.VISIBLE);
                                //							tv.setText("限购"+shangpinList.get(index).getPerlim()+"份");
                                //						}
//						setMsg("jia1", amount, index);
//						setMsg("zongjia1",total,0);


                                setMsg1("jia1", amount, index);
                                setMsg1("zongjia1", total, 0);
                                //						setMsg("qingchu",""+goodsNum,index);
                            } else {
                                Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
                            }
                        } catch (JSONException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }

                });
    }

    //	private void addgoodscat(int index, EditText editText) {
    //		if (Integer.parseInt(editText.getText().toString()) <= 0) {
    //			Toast.makeText(context, "去购物车删除!", Toast.LENGTH_SHORT).show();
    //			return;
    //		}
    ////		if (Integer.parseInt(editText.getText().toString()) > Integer.parseInt(shangpinList.get(index).getPerlim())) {
    ////			Toast.makeText(context, "限购"+shangpinList.get(index).getPerlim()+"份", Toast.LENGTH_SHORT).show();
    ////			return;
    ////		}
    //		SharedPreferences sp=context.getSharedPreferences("spReg", Context.MODE_PRIVATE);
    //		String token = sp.getString("data", "");
    //		Log.i("info", "token"+"token"+token);
    //		if (httpTools == null) {
    //			httpTools = new HttpTools(context);
    //		}
    //		httpTools.addgoodscat(token, shangpinList.get(index).getId(),editText
    //				.getText().toString() , new JsonHttpResponseHandler(){
    //			public void onSuccess(int statusCode, Header[] headers,
    //					JSONObject response) {
    //				// TODO Auto-generated method stub
    //				super.onSuccess(statusCode, headers, response);
    //				try {
    //					//							Log.i("zq",response.toString());
    //					boolean code = response.getBoolean("code");
    //					String msg = response.getString("msg");
    //					if(code==true){
    //						Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
    //					}else{
    //						Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
    //					}
    //				} catch (JSONException e) {
    //					e.printStackTrace();
    //				}
    //			}
    //		});
    //	}

    /**
     * 减少商品
     */
    private void lessGoods(final int index, final EditText editText, int goodsNum, final TextView tv) {
        if (NetWorkUtil.isNetwork(context) == false) {
            Toast.makeText(context, "当前网络不可用", Toast.LENGTH_SHORT).show();
            return;
        }
        if ("".equals(editText.getText().toString())) {
            editText.setText(0 + "");
            goodsNum = 0;
        }
        SharedPreferences sp = context.getSharedPreferences("spReg",
                Context.MODE_PRIVATE);
        String token = sp.getString("data", "");

        if (httpTools == null) {
            httpTools = new HttpTools(context);
        }

        //		if(goodsNum==1)
        //		{
        //			deletegoods(index, goodsNum);
        //			goodsNum=0;
        //			editText.setText("0");
        //			return;
        ////			Toast.makeText(context, "去购物车中删除", Toast.LENGTH_SHORT).show();
        ////			return;
        ////			setMsg("jia", "0", index);
        ////			gouwucheList.remove(index);
        ////			notifyDataSetChanged();
        //		}
        //		else if(goodsNum<=0)
        //		{
        ////			deletegoods(index);
        //			Toast.makeText(context, "数量不能小于0", Toast.LENGTH_SHORT).show();
        //			return;
        ////			setMsg("jia", "0", index);
        ////			gouwucheList.remove(index);
        ////			notifyDataSetChanged();
        //		}
        //		goodsNum--;
        httpTools.addgoodscat(token, shangpinList.get(index).getId(), goodsNum + "",
                new JsonHttpResponseHandler() {

                    @Override
                    public void onSuccess(int statusCode, Header[] headers,
                                          JSONObject response) {
                        // TODO Auto-generated method stub
                        super.onSuccess(statusCode, headers, response);
                        try {
                            Log.i("info", response.toString());
                            boolean code = response.getBoolean("code");
                            String msg = response.getString("msg");
                            int goodsNum = Integer.parseInt(editText.getText().toString());
                            if (code == true) {
                                JSONObject data = response.getJSONObject("data");
                                String amount = data.getString("amount");
                                String total = data.getString("total");
                                int goodsNum2 = Integer.parseInt(editText.getText().toString());
                                //						goodsNum--;
                                //						shangpinList.get(index).setAmount(""+goodsNum);
                                editText.setText(goodsNum + "");
                                int lim = Integer.parseInt(shangpinList.get(index).getStock());
                                //						if(goodsNum<=lim){
                                //							tv.setVisibility(View.VISIBLE);
                                //							tv.setText("仅剩"+shangpinList.get(index).getStock()+"份");
                                //						}
//						setMsg("jian1", amount, index);
//						setMsg("zongjia1",total,0);


                                setMsg1("jian1", amount, index);
                                setMsg1("zongjia1", total, 0);
                                //						setMsg("qingchu",""+goodsNum,index);
                            } else {
                                //						Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
                            }
                        } catch (JSONException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }

                });
    }

    /**
     * 移除商品
     */
    private void deletegoods(final int index, int goodsNum) {
        if (NetWorkUtil.isNetwork(context) == false) {
            Toast.makeText(context, "当前网络不可用", Toast.LENGTH_SHORT).show();
            return;
        }
        SharedPreferences sp = context.getSharedPreferences("spReg",
                Context.MODE_PRIVATE);
        String token = sp.getString("data", "");

        if (httpTools == null) {
            httpTools = new HttpTools(context);
        }
        httpTools.remove(token, shangpinList.get(index).getId(),
                new JsonHttpResponseHandler() {
                    @Override
                    public void onSuccess(int statusCode, Header[] headers,
                                          JSONObject response) {
                        super.onSuccess(statusCode, headers, response);
                        Log.e("zq", "删除------------" + response.toString());
                        try {
                            boolean code = response.getBoolean("code");
                            String msg = response.getString("msg");
                            if (code == true) {
                                JSONObject data = response.getJSONObject("data");
                                String amount = data.getString("amount");
                                String total = data.getString("total");
                                //								Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
                                //								goodsNum=0;
                                //								gouwucheList.remove(index);
                                //								notifyDataSetChanged();
//						setMsg("qingchu1",amount,index);
//						setMsg("zongjia1",total,0);


                                setMsg1("qingchu1", amount, index);
                                setMsg1("zongjia1", total, 0);
                            } else {
                                Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
                            }
                        } catch (JSONException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }

                });
    }

    private void setMsg(String sopt, String str, int index) {
        Message message = Message.obtain();
        Bundle bundle = new Bundle();
        bundle.putString("sopt1", sopt);
        bundle.putString("str1", str);
        bundle.putInt("index1", index);
        message.obj = bundle;
        GoodsTwoSortActivity.myhanler.sendMessage(message);
//		FanqiedingcanActivity.myhanler.sendMessage(message);
    }

    private void setMsg1(String sopt, String str, int index) {
        Message message = Message.obtain();
        Bundle bundle = new Bundle();
        bundle.putString("sopt1", sopt);
        bundle.putString("str1", str);
        bundle.putInt("index1", index);
        message.obj = bundle;
//		GoodsTwoSortActivity.myhanler.sendMessage(message);
        FanqiedingcanActivity.myhanler.sendMessage(message);
    }

    class ViewHandle {
        /**
         * 图片
         */
        ImageView iv_shangpin;
        /**
         * 商品名
         */
        TextView tv_shangpinming;
        /**
         * 价格
         */
        TextView tv_price;
        /**
         * 加
         */
        ImageButton ib_add;
        /**
         * 减
         */
        ImageButton ib_less;
        /**
         * 数量
         */
        EditText et_amout;
        /**
         * 销量
         */
        TextView tv_xiangliang;
        /**
         * 限购
         */
        TextView tv_xiangou;
        //		TextView tv_guige;
    }

}



